// components/project/ProjectDetailDialog.tsx
"use client"

import React, { useState } from 'react'
import { Calendar, MapPin, DollarSign, Target, FileText, Download, Loader2, Upload } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Label } from '@/components/ui/label'
import { useProjects } from '@/hooks/project'
import type { Project } from '@/types/project'

// 项目状态配置
const PROJECT_STATUS: { value: string; label: string; color: string }[] = [
  { value: "进行中", label: "进行中", color: "bg-green-100 text-green-800" },
  { value: "已完成", label: "已完成", color: "bg-gray-100 text-gray-800" }
]

interface ProjectDetailDialogProps {
  project: Project | null
  isOpen: boolean
  onClose: () => void
}

export function ProjectDetailDialog({ project, isOpen, onClose }: ProjectDetailDialogProps) {
  const { downloadAttachment } = useProjects()
  const [downloadingFiles, setDownloadingFiles] = useState<Set<string>>(new Set())
  const [downloadMessage, setDownloadMessage] = useState<{ type: 'success' | 'error', text: string } | null>(null)

  if (!isOpen || !project) return null

  const statusConfig = PROJECT_STATUS.find(s => s.value === project.status)

  // 处理文件下载
  const handleDownloadAttachment = async (attachmentId: string, fileName: string) => {
    setDownloadingFiles(prev => new Set(prev).add(attachmentId))
    setDownloadMessage(null)
    
    try {
      await downloadAttachment(project.id, attachmentId, fileName)
      setDownloadMessage({ type: 'success', text: `文件 "${fileName}" 下载成功` })
      
      // 3秒后自动清除成功消息
      setTimeout(() => {
        setDownloadMessage(null)
      }, 3000)
    } catch (error: any) {
      console.error('下载失败:', error)
      setDownloadMessage({ 
        type: 'error', 
        text: `下载失败: ${error.message || '未知错误'}` 
      })
    } finally {
      setDownloadingFiles(prev => {
        const newSet = new Set(prev)
        newSet.delete(attachmentId)
        return newSet
      })
    }
  }

  // 格式化文件大小
  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return '0 Bytes'
    const k = 1024
    const sizes = ['Bytes', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }

  // 格式化上传时间
  const formatUploadTime = (dateString: string): string => {
    try {
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    } catch {
      return dateString
    }
  }

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-[9999]">
      <div className="bg-white rounded-lg p-6 w-full max-w-4xl max-h-[90vh] overflow-y-auto relative z-[10000]">
        <div className="mb-6">
          <h2 className="text-2xl font-bold">项目详情</h2>
        </div>
        


        <div className="space-y-6">
          {/* 基本信息区域 */}
          <div className="border rounded-lg p-4 space-y-4 bg-blue-50/30">
            <h3 className="font-semibold text-lg mb-4 flex items-center text-blue-700">
              <FileText className="w-5 h-5 mr-2" />
              基本信息
            </h3>
            
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Label className="text-sm font-medium text-gray-700">项目名称</Label>
                <div className="mt-1 p-3 bg-white border rounded-md">
                  <p className="text-sm font-medium">{project.name}</p>
                </div>
              </div>
              
              <div>
                <Label className="text-sm font-medium text-gray-700">项目负责人</Label>
                <div className="mt-1 p-3 bg-white border rounded-md">
                  <p className="text-sm">{project.manager || '未指定'}</p>
                </div>
              </div>
              
              <div>
                <Label className="text-sm font-medium text-gray-700">作物类型</Label>
                <div className="mt-1 p-3 bg-white border rounded-md">
                  <p className="text-sm">{project.crop_type}</p>
                </div>
              </div>
              
              <div>
                <Label className="text-sm font-medium text-gray-700">项目状态</Label>
                <div className="mt-1 p-3 bg-white border rounded-md">
                  <Badge className={statusConfig?.color}>
                    {statusConfig?.label}
                  </Badge>
                </div>
              </div>
              
              <div>
                <Label className="text-sm font-medium text-gray-700">所属实验室</Label>
                <div className="mt-1 p-3 bg-white border rounded-md">
                  <p className="text-sm">{project.laboratory_name || '未指定'}</p>
                </div>
              </div>
            </div>

            <div>
              <Label className="text-sm font-medium text-gray-700">项目描述</Label>
              <div className="mt-1 p-3 bg-white border rounded-md min-h-[80px]">
                <p className="text-sm whitespace-pre-wrap">{project.description || '暂无描述'}</p>
              </div>
            </div>
          </div>

          {/* 时间和地点区域 */}
          <div className="border rounded-lg p-4 space-y-4 bg-green-50/30">
            <h3 className="font-semibold text-lg mb-4 flex items-center text-green-700">
              <MapPin className="w-5 h-5 mr-2" />
              时间和地点
            </h3>
            
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div>
                <Label className="text-sm font-medium text-gray-700">开始日期</Label>
                <div className="mt-1 p-3 bg-white border rounded-md flex items-center">
                  <Calendar className="w-4 h-4 mr-2 text-gray-400" />
                  <p className="text-sm">{project.start_date || '未设定'}</p>
                </div>
              </div>
              
              <div>
                <Label className="text-sm font-medium text-gray-700">结束日期</Label>
                <div className="mt-1 p-3 bg-white border rounded-md flex items-center">
                  <Calendar className="w-4 h-4 mr-2 text-gray-400" />
                  <p className="text-sm">{project.end_date || '未设定'}</p>
                </div>
              </div>
              
              <div>
                <Label className="text-sm font-medium text-gray-700">项目地点</Label>
                <div className="mt-1 p-3 bg-white border rounded-md flex items-center">
                  <MapPin className="w-4 h-4 mr-2 text-gray-400" />
                  <p className="text-sm">{project.location || '未指定'}</p>
                </div>
              </div>
            </div>
            
            <div>
              <Label className="text-sm font-medium text-gray-700">创建时间</Label>
              <div className="mt-1 p-3 bg-white border rounded-md flex items-center">
                <Calendar className="w-4 h-4 mr-2 text-gray-400" />
                <p className="text-sm">{project.created_at}</p>
              </div>
            </div>
          </div>

          {/* 预算和目标区域 */}
          <div className="border rounded-lg p-4 space-y-4 bg-yellow-50/30">
            <h3 className="font-semibold text-lg mb-4 flex items-center text-yellow-700">
              <Target className="w-5 h-5 mr-2" />
              预算和目标
            </h3>
            
            <div>
              <Label className="text-sm font-medium text-gray-700">项目预算（元）</Label>
              <div className="mt-1 p-3 bg-white border rounded-md flex items-center">
                <DollarSign className="w-4 h-4 mr-2 text-gray-400" />
                <p className="text-sm font-medium">¥{project.budget.toLocaleString()}</p>
              </div>
            </div>

            {project.objectives && project.objectives.length > 0 && (
              <div>
                <Label className="text-sm font-medium text-gray-700">项目目标</Label>
                <div className="mt-1 p-3 bg-white border rounded-md space-y-2">
                  {project.objectives.map((objective, index) => (
                    <div key={index} className="flex items-start text-sm">
                      <Target className="w-4 h-4 mr-2 mt-0.5 text-yellow-600 flex-shrink-0" />
                      <span>{objective}</span>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>

          {/* 附件管理区域 */}
          {project.attachments && project.attachments.length > 0 && (
            <div className="border rounded-lg p-4 space-y-4 bg-purple-50/30">
              <h3 className="font-semibold text-lg mb-4 flex items-center text-purple-700">
                <Upload className="w-5 h-5 mr-2" />
                项目附件 ({project.attachments.length})
              </h3>
              
              {/* 下载状态消息 */}
              {downloadMessage && (
                <div className={`p-3 rounded-lg ${
                  downloadMessage.type === 'success' 
                    ? 'bg-green-50 border border-green-200 text-green-700' 
                    : 'bg-red-50 border border-red-200 text-red-700'
                }`}>
                  <p className="text-sm">{downloadMessage.text}</p>
                </div>
              )}
              
              <div className="space-y-2 max-h-60 overflow-y-auto">
                {project.attachments.map((attachment) => (
                  <div key={attachment.id} className="flex items-center justify-between p-3 bg-white border rounded hover:bg-gray-50">
                    <div className="flex items-center flex-1 min-w-0">
                      <FileText className="w-4 h-4 mr-2 text-purple-500 flex-shrink-0" />
                      <div className="flex-1 min-w-0">
                        <p className="text-sm font-medium truncate" title={attachment.name}>
                          {attachment.name}
                        </p>
                        <p className="text-xs text-gray-500">
                          {formatFileSize(attachment.size)} · {formatUploadTime(attachment.uploaded_at)}
                          {attachment.uploaded_by_name && ` · 上传者：${attachment.uploaded_by_name}`}
                        </p>
                      </div>
                    </div>
                    <Button
                      variant="ghost"
                      size="sm"
                      disabled={downloadingFiles.has(attachment.id)}
                      onClick={() => handleDownloadAttachment(attachment.id, attachment.name)}
                      className="h-8 w-8 p-0 hover:bg-blue-50 hover:text-blue-600"
                      title="下载文件"
                    >
                      {downloadingFiles.has(attachment.id) ? (
                        <Loader2 className="w-4 h-4 animate-spin" />
                      ) : (
                        <Download className="w-4 h-4" />
                      )}
                    </Button>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
        
        {/* 底部操作按钮 */}
        <div className="flex justify-end pt-6">
          <Button variant="outline" onClick={onClose}>
            关闭
          </Button>
        </div>
      </div>
    </div>
  )
}